<template>
    <div>
        <div class="hen">
            <el-row class="hengfu">
                <el-col :span="12">
                    <el-page-header @back="goBack">
                        <template #content>
                            <el-breadcrumb-item>安排·新增</el-breadcrumb-item>
                        </template>
                    </el-page-header>
                </el-col>
            </el-row>
        </div>

        <div class="tab">
            <div class="trr">
                <el-descriptions v-loading="loading" title="安排·考试" :column="2" border>
                    <el-descriptions-item label="安排名称" label-align="right" align="left" label-class-name="my-label"
                        class-name="my-content" width="150px">
                        <el-input style="width: 40vh;" v-model="name" placeholder="请输入题库名称" />
                    </el-descriptions-item>
                    <el-descriptions-item width="150px" label="考试时间" label-align="right" align="left">
                        <el-date-picker v-model="times" type="datetimerange" range-separator="至" start-placeholder="开始时间"
                            end-placeholder="结束时间" />
                    </el-descriptions-item>
                    <el-descriptions-item label="选择试卷" :span=2 label-align="right" width="150px" align="left">
                        <el-row class="hengfu">
                            <el-col :span="12">
                                <el-tag v-if="shijuanname != ''">{{ shijuanname }}</el-tag>
                                <el-tag v-else>暂无选择</el-tag>
                            </el-col>
                            <el-col :span="12">
                                <el-button type="warning" @click="dialogVisiblesA = true" plain>去选择</el-button>
                            </el-col>
                        </el-row>
                    </el-descriptions-item>

                    <el-descriptions-item label="选择组织" :span=2 label-align="right" width="150px" align="left">
                        <el-row class="hengfu">
                            <el-col :span="12">
                                <el-tag v-for="obj in item" :key="obj.id">
                                    {{ obj.name }}
                                </el-tag>
                            </el-col>
                            <el-col :span="12">
                                <el-button type="warning" @click="dialogVisiblesB = true" plain>去选择</el-button>
                            </el-col>
                        </el-row>
                    </el-descriptions-item>


                    <el-descriptions-item label="描述" :span=2 label-align="right" align="left">
                        <el-input v-model="explain" :rows="2" type="textarea" placeholder="题库描述" />
                    </el-descriptions-item>
                    <el-descriptions-item label="操作" label-align="right" align="left">
                        <el-button 
                            color="#0EA06F" size="large" type="primary" plain @click="add">新增试题</el-button>
                    </el-descriptions-item>
                </el-descriptions>
            </div>
        </div>

        <!-- 弹出框试卷 -->
        <el-dialog v-model="dialogVisiblesA" :show-close="true">
            <template #header="{ titleId, titleClass }">
                <div class="my-header">
                    <h4 :id="titleId" :class="titleClass" style="text-align: left;margin-top: 10px;">选择试卷</h4>
                </div>
            </template>
            <div style=" margin: auto;margin-top: -3vh;">
                <div class="grid-content">
                    <el-table :data="tableData" style="width: 100%">
                        <el-table-column type="index" label="序号" width="60" />
                        <el-table-column prop="name" label="试卷名" width="180" />
                        <el-table-column prop="lv" label="难度" width="120" />
                        <el-table-column prop="count" label="题目" />
                        <el-table-column prop="labels" label="标签" />
                        <el-table-column prop="useCount" label="使用次数" />
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button size="small" type="primary" @click="xuanzhe(scope.row)">选择</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </el-dialog>
        <!-- 弹出框组织 -->
        <el-dialog v-model="dialogVisiblesB" :show-close="true">
            <template #header="{ titleId, titleClass }">
                <div class="my-header">
                    <h4 :id="titleId" :class="titleClass" style="text-align: left;margin-top: 10px;">选择组织</h4>
                </div>
            </template>
            <div style=" margin: auto;margin-top: -3vh;">
                <div class="grid-content">
                    <el-tree :data="datas" :default-checked-keys="checked" :props="defaultProps" :check-strictly="true"
                        show-checkbox @node-click="handleNodeClick" node-key='id' @check-change="change"
                        :default-expand-all="true" />

                </div>
                <div style="margin-top: 2vh;">
                    <el-button size="small" type="primary" @click="sure">确定</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import type { TypeArrangeAddDto } from '../../../type/arrangeAdd'
import { defineComponent, onMounted, reactive, toRefs } from 'vue'
import { GetTestPapers } from '../../../api/testpaper/testpaper'
import { ElNotification } from 'element-plus'
import { GetOrganizations } from '../../../api/user/user'
import { AddArrange } from '../../../api/arrange/arrange'
import { ElMessageBox } from 'element-plus';
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router';


export default defineComponent({
    setup() {
        const router = useRouter();

        const data = reactive({
            obj: {
                page: 1,        // 第几页 
                limit: 5,       // 多少条数据
                key: '',        // 题库查询条件 
                index: 0,       // 多少条数据   
            },
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            loading: true,  // 加载屏 
            checkList: [],  //多选框
            explain: '',     //描述框  
            name: '',        //题库名
            times: [],        //时间
            labels: [],       //标签
            disabled: true,    //是否禁用
            dialogVisiblesA: false, //试卷弹出框
            dialogVisiblesB: false, //组织弹出框
            limit: 10,//每页显示条数
            page: 1,//当前页
            total: 0,//总条数
            tableData: [], //存放数据
            datas: [],//树形数据
            checked: [],
            item: [],
            orgids: [], //组织集合
            tpids: [],//试卷集合
            shijuantid: "",
            shijuanname: ""
        })

        const events = {
            //树形菜单
            org() {
                GetOrganizations({
                    page: data.page,
                    limit: 999,
                }).then((res: any) => {
                    console.log("获取组织-----", res)
                    if (res.result == 0) {
                        data.datas = res.data.data
                    }
                })
            },
            //节点选中时值发生变化
            change(val: any, item: any) {
                // console.log(item)
                // console.log(val)
                if (item == true) {
                    data.checked.push(val.id)
                }
                if (item == true) {
                    data.item.push(val)
                    console.log(data.item)
                } else {
                    for (let i = 0; i < data.checked.length; i++) {
                        if (val.id == data.checked[i]) {
                            data.checked.splice(i, 1)
                        }
                        if (data.item.length > 0) {
                            if (val.id == data.item[i].id) {
                                data.item.splice(i, 1)
                            }
                        }
                    }
                }
            },
            //返回上一级
            goBack() {
                window.history.go(-1)
            },
            //监听
            handleNodeClick() {

            },
            //点击确定
            sure(obj: any) {
                console.log("<><><obj><><>",data.item)
                data.dialogVisiblesB = false
                data.orgids=data.item
                console.log(">>>>>>data.orgids>>>>>..",data.orgids)
            },
            //选择试卷
            xuanzhe(datas: any) {
                data.tpids.push(datas);
                for (let i = 0; i < data.tpids.length; i++) {
                    data.shijuantid = data.tpids[i].id;
                    data.shijuanname = data.tpids[i].name;
                }
                console.log("拿到tpids", data.tpids);
                data.dialogVisiblesA = false;
            },
            //时间转换，时间转换 Wed Sep 16 2020 00:00:00 GMT+0800 (中国标准时间)
            dateFormat(dateData: any) {
                var date = new Date(dateData)
                var y = date.getFullYear()
                var m: any = date.getMonth() + 1
                m = m < 10 ? ('0' + m) : m
                var d: any = date.getDate()
                d = d < 10 ? ('0' + d) : d
                //时分秒
                var h: any = date.getHours();
                h = h < 10 ? ('0' + h) : h
                var mm: any = date.getMinutes();
                mm = mm < 10 ? ('0' + mm) : mm
                var s: any = date.getSeconds();
                s = s < 10 ? ('0' + s) : s
                const time = y + '/' + m + '/' + d + ' ' + h + ":" + mm + ':' + s
                return time
            },
            //当前年月日
            getCurrentTime() {
                //获取当前时间并打印
                var date = "";
                let yy = new Date().getFullYear();
                let mm: any = new Date().getMonth() + 1;
                mm = mm < 10 ? ('0' + mm) : mm
                let dd: any = new Date().getDate();
                dd = dd < 10 ? ('0' + dd) : dd
                date = yy + '/' + mm + '/' + dd
                return date
            },
            //当前时分秒
            getCurrent() {
                //获取当前时间并打印
                var date = "";
                let hh = new Date().getHours();
                let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
                let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
                date = hh + ':' + mf + ':' + ss;
                return date
            },
            add() {
                let ids:any = [];
                data.orgids.forEach((item:any) => {
                    ids.push(item.id)
                })
                console.log(">>>>>>>>>>>>>>>>>>.",ids)
                
                //当前时间
                var ymd = parseInt(events.getCurrentTime().split(' ')[0].split('/').join(""))  //年月日
                var hms = events.getCurrent().split(':').join("") //时分秒
                console.log("今日时分秒", hms)
                //开始时间
                var Kymd = parseInt(events.dateFormat(data.times[0]).split(' ')[0].split('/').join(""))  //年月日
                var Khms = events.dateFormat(data.times[0]).split(' ')[1].split(':').join("")  //时分秒
                console.log("开始时分秒", Khms)
                //结束时间
                var Jymd = parseInt(events.dateFormat(data.times[1]).split(' ')[0].split('/').join(""))  //年月日
                if (Kymd < ymd) {
                    ElMessage({
                        message: '开始时间不能小于今日时间',
                        type: 'error',
                    })
                    return
                }
                if (Kymd == ymd) {
                    if (Khms < hms) {
                        ElMessage({
                            message: '开始时间不允许小于当前时间',
                            type: 'error',
                        })
                        return
                    }
                }
                if (Jymd - Kymd > 7) {
                    ElMessage({
                        message: '最大时间范围7天',
                        type: 'error',
                    })
                    return
                }
                //新增
                AddArrange({
                    name: data.name,
                    beginTime: data.times[0],
                    endTime: data.times[1],
                    tpid: data.shijuantid,
                    orgids: ids.join(","),
                    explain: data.explain,
                }).then((res: any) => {
                    if(res.result==0){
                        ElMessage({
                            message: '新增成功',
                            type: 'success',
                        })   
                        router.push("/exam/arrange")
                    }else{
                        ElMessage({
                            message: '新增失败',
                            type: 'error',
                        }) 
                    }
                })
            },

            // 获取试卷列表
            GetLabel() {
                GetTestPapers({
                    page: data.obj.page,
                    limit: data.obj.limit,
                    key: '',
                    isBan: 0,
                    isPublish: 1
                }).then((res: any) => {
                    if (res.result == 0) {
                        data.loading = false
                        data.tableData = res.data.data
                    }
                    console.log(res)
                })
            }

        }

        onMounted(() => {
            events.GetLabel()
            events.org()
        })

        return {
            ...toRefs(data),
            ...events
        }

    },
})
</script>

<style scoped>
/* 背景 */
.tab {
    margin-top: 2vh;
    height: 78vh;
    /* background-color: rgb(239, 240, 242); */
    border: 1px solid darkgray;
    box-shadow: 0px 0px 2px rgb(188, 185, 185);
    border-radius: 5px;
}

/* 按钮样式 */
.grid-content {
    margin: auto;
    margin-top: 2vh;
    border-radius: 5px;
    background-color: rgb(251, 251, 251);
    width: 95%;
    line-height: 45px;
    text-align: left;
    padding: 10px;
    border: 1px solid darkgray;
    box-shadow: 0px 0px 1px grey;
}

.flex {
    float: right;
    /* margin-right: 2vh; */
}

.trr {
    margin: auto;
    margin-top: 2vh;
    border-radius: 5px;
    padding: 10px;
    height: 70vh;
    width: 95%;
    background-color: rgb(251, 251, 251);
    ;
    border: 1px solid darkgray;
    box-shadow: 0px 0px 1px grey;
}
</style>
